<template>
  <div class='table'>
    <ui-container style="width:100%">
      <div class='t_top'>
        <el-select v-model="type" placeholder="请选择" size="small">
          <el-option label="全部" value="null"></el-option>
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-input
          placeholder="用户名"
          v-model="inputNo"
          size="small"
          clearable style="width:200px">
        </el-input>
        <el-button type="primary" size="small" @click="search()" >查询</el-button>
      </div>
    </ui-container>
    <ui-container style='margin-top:15px' v-loading="loading">
      <div style="text-align:right;" class="btn-row">
        <el-button type="success" size="small" @click="handleBill">查看账单</el-button>
        <el-button type="success" size="small" @click="add">设置账单</el-button>
        <el-button type="danger" size="small" @click="handleClick">重置密码</el-button>
        <el-button type="success" size="small" @click="handleExamine">审核店铺</el-button>
        <el-button type="danger" size="small" @click="del">删除用户</el-button>
      </div>
      <div class='t_bottom' style="width:100%; font-size:14px;">
        <el-table
          ref='multipleTable'
          :data='tableData'
          tooltip-effect='light'
          style='width:100%'
          border
        >
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column prop="HeadUrl" label="店家logo" width='140'>
            <template slot-scope="scope">
              <img :src="scope.row.HeadUrl" style="width:120px;height:120px;" />
            </template>
          </el-table-column>
          <el-table-column prop='UserName' label='用户名' width='120'></el-table-column>
          <el-table-column prop='Phone' label='联系方式' width='120'></el-table-column>
          <el-table-column prop='AuditStatusStr' label='审核状态' width='120'></el-table-column>
          <el-table-column prop='Floor' label='楼层' width='100'>
          </el-table-column>
          <el-table-column prop='Address' label='楼层地址' width='120'>
          </el-table-column>
          <el-table-column prop='ShopType' label='店铺类型' width='120'>
          </el-table-column>
          <el-table-column prop='ShopDetail' label='商户简介' show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop='CreateTime' label='入驻时间' width='160'></el-table-column>
        </el-table>
        <div class="pagination-row">
          <el-pagination
            background
            layout="total,prev, pager, next,sizes"
            :total="totalNum">
          </el-pagination>
        </div>
      </div>
    </ui-container>
    <el-dialog title="上传账单" :visible.sync="addDialog" width="30%">
      <el-form ref="form" :model="form" label-width="120px">

        <div>
          <span style="font-size:12px;color:red;">提示：只能上传excle文件</span>
        <a download :href="require('assets/images/账单.xlsx')" style="font-size:12px;"> 下载账单模板</a>
        </div>
        <el-upload
          name="file"
          class="avatar-uploader"
          style="margin-top:10px;"
          :data="fileParams"
          ref="upload"
          :action="uploadUrl"
          :headers="{authorization:token}"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleFileError"
          :auto-upload="true"
          :before-upload="beforeAvatarUpload">
          <el-button size="small" type="primary">点击上传</el-button>

        </el-upload>
        <!-- <div style="text-align:right;">
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">保存</el-button>
        </div> -->
        <!-- <el-form-item label="账单类型" prop="Type" required>
          <el-select v-model="form.Type" placeholder="请选择账单类型" size="small">
            <el-option label="租金" value="0"></el-option>
            <el-option label="管理费" value="1"></el-option>
            <el-option label="电费" value="2"></el-option>
            <el-option label="推广费" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="UnitPrice" required>
          <el-input-number v-model="form.UnitPrice" :precision="2" :step="0.1" size="small"></el-input-number>
        </el-form-item>
        <el-form-item label="总费" prop="TotalFee" required>
          <el-input-number v-model="form.TotalFee" :precision="2" :step="0.1" size="small"></el-input-number>
        </el-form-item>
        <el-form-item label="账单月份" prop="PayDate" required>
          <el-date-picker
            v-model="form.PayDate"
            type="month"
            size="small"
            format="yyyy-MM"
            placeholder="选择账单月份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="面积" prop="Area" required>
          <el-input-number v-model="form.Area" :precision="2" :step="0.1" size="small"></el-input-number>
        </el-form-item>
        <el-form-item label="最后付款日" prop="LastDate" required>
          <el-date-picker
            v-model="form.LastDate"
            type="date"
            size="small"
            format="yyyy-MM-dd"
            placeholder="选择最后付款日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="Remarks">
          <el-input type="textarea" v-model="form.Remarks" size="small"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">保存</el-button>
          <el-button  @click="handleRest()">清空</el-button>
        </el-form-item> -->
      </el-form>
    </el-dialog>
    <el-dialog title="店铺账单管理" :visible.sync="dialog" width="60%">
      <el-table
        ref='multipleTable1'
        :data='billData'
        tooltip-effect='light'
        style='width:100%;'
        height="400"
        border
      >
        <el-table-column prop='PayDate' label='账单季度' width='100'></el-table-column>
        <el-table-column prop='TypeStr' label='账单类型' width='100'></el-table-column>
        <el-table-column prop='UnitPrice' label='单价' width='100'></el-table-column>
        <el-table-column prop='TotalFee' label='总费' width='100'></el-table-column>
        <el-table-column prop='Area' label='面积' width='120'></el-table-column>
        <el-table-column prop='LastDateStr' label='最后付款日' width='120'></el-table-column>
        <el-table-column prop='isok' label='操作' >
            <template slot-scope="scope">
              <el-button type="text" @click="handleBillClick(scope.row.Id)">确认支付</el-button>
              <el-button type="text" style="color:red" @click="handleDelBill(scope.row.Id)">作废账单</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="审核店家" :visible.sync="dialogFormVisible" width="600">
        <div style="text-align: center;width: 100%">
      <el-button type="success" style="width:250px;height:60px;font-size:20px;" :loading="loading" @click="examine(1)">审核通过</el-button>
      <el-button type="danger" style="width:250px;height:60px;font-size:20px;" :loading="loading" @click="examine(2)">审核失败</el-button>
        </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="small">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type='text/javascript'>
import {cookieStorage} from 'src/common/storage'
export default {
  name: 'shopPage',
  data () {
    return {
        typeList:[{
          value: 0,
          label: '待审核'
        }, {
          value: 1,
          label: '审核通过'
        }, {
          value: 2,
          label: '审核失败'
        }],
      type: null,
      loading: false,
      dialog: false,
      addDialog: false,
      inputNo: '',
      inputName: '',
      editId:0,
      tableData: [],
      billData: [],
      totalNum:0,
      pageIndex:1,
      pageSize:10,
      token:cookieStorage.get('authorization'),
      dialogFormVisible: false,
      imageUrl: '',
      form: {
        Type:'',
        UnitPrice:0,
        TotalFee:0,
        Area:0,
        PayDate:'',
        LastDate:''
        },
        rules: {
          Type: [
            { required: true, message: '请选择账单类型', trigger: 'change' }
          ],
          UnitPrice: [
            { required: true, message: '请输入单价', trigger: 'blur' }
          ],
          TotalFee: [
            { required: true, message: '请输入总费', trigger: 'blur' },
          ],
          Area: [
            { required: true, message: '请输入面积', trigger: 'blur' }
          ],
          PayDate: [
            { required: true, message: '请选择账单月份', trigger: 'change' }
          ],
          LastDate: [
            { required: true, message: '请选择最后付款日', trigger: 'change' }
          ]
        },
        uploadUrl: '',
        fileParams: {
          shopId:''
        }
    }
  },
  mounted () {
     this.init();
  },
  methods: {
    search(){
      this.pageIndex = 1;
      this.init();
    },
    init(){
      this.loading=true;
      var data = {
          UserName: this.inputNo,
          AuditStatus: eval(this.type),
          PageIndex: this.pageIndex,
          PageSize: this.pageSize
        };

      this.$api.shop.page(data).then((rs) => {
        console.log(rs)
        this.tableData = rs.Data.Data;
        this.totalNum = rs.Data.TotalNum;
        this.loading=false;
      }).catch((res) =>{this.loading=false;})
    },
    tabsClick(tab, event){
        this.init()
    },
    handleClick(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据重置密码！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      this.open(id)
    },
    handleRest(){
      this.clearForm();
    },
    clearForm(){
      //this.$refs['form'].resetFields();
      this.form.Type = '';
      this.form.UnitPrice = 0;
      this.form.TotalFee = 0;
      this.form.Area = 0;
      this.form.PayDate = '';
      this.form.LastDate = '';
    },
    handleBill(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      this.editId=id;
      this.dialog=true;
      this.$api.shop.getNoPayBills(id).then((rs) => {
        this.billData = rs.Data
      })
    },
    handleBillClick(id){
      this.$confirm('是否确认此账单已付款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.shop.confirm(id).then((rs) => {
          if(rs.IsSuccess){
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.handleBill();
          }
        })
      }).catch(() => {
      });
    },
    handleDelBill(id){
      this.$confirm('此操作将作废此账单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.shop.del(id).then((rs) => {
          if(rs.IsSuccess){
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.handleBill();
          }
        });
      }).catch(() => {
      });
    },
    examine(status){
        this.loading=true;
        let data = {
              shopId:this.editId,
              status:status
          };
        this.$api.shop.examine(data).then((rs) => {
        if(rs.IsSuccess){
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.dialogFormVisible=false;
          this.init();
          }
        }).catch((res) =>{this.loading=false;})
    },
    open(index) {
      this.$confirm('此操作将店铺重置密码为000000 , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          let data = {
              shopId:index
          };
        this.$api.shop.reset(data).then((rs) => {
        if(rs.IsSuccess){
          this.$message({
            type: 'success',
            message: '重置成功!'
          });
          this.init();
          }
        }).catch((res) =>{})
      }).catch(() => {
      });
    },
    updateStatus(row){
      this.loading=true;
      this.$api.shopActivity.enable(row.Id, !row.IsEnable).then((rs) => {
        this.init();
      }).catch((res) =>{this.loading=false;})
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.ShopId=this.editId;
          this.form.PayDate=this.msToYearMonth(this.form.PayDate);
          this.form.LastDate=this.msToDate(this.form.LastDate).withoutTime;
          this.$api.shop.form(this.form).then((rs) => {
            if(rs.IsSuccess){
              this.$message({
                type: 'success',
                message: '提交成功!'
              });
              this.addDialog = false;
            }
          }).catch((res) =>{this.loading=false;this.dialogFormVisible=false;})
        } else {
          this.$message.error('提交失败！');
          this.dialogFormVisible=false;
          return false;
        }
      });
    },
    handleExamine(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据进行审核！");
          return;
      }
      let ids = [];
      let auditStatus = selected.map(m => m.AuditStatus)[0];
      if (auditStatus !== 0) {
          this.$message.error("已经审核的店铺不能重复审核！");
          return;
      }
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      this.editId=id;
      this.dialogFormVisible=true;
    },
    del(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一个商户数据删除！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      let params ={
        userId: id
      }
      this.$confirm('此操作将删除用户数据 , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.user.deleteCompanyUserInfo(params).then((rs) => {
          if(rs.IsSuccess){
            this.$message({
              type: 'success',
              message: '删除成功！'
            });
            this.init()
          }
        }).catch((res) =>{
        })
      }).catch(() => {
      });
    },
    add(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      this.editId=id;
      this.fileParams.shopId = id;
      this.uploadUrl = `/api/companyBill/${id}/upload`;
      //this.clearForm();
      this.addDialog = true;
    },
    msToYearMonth(msec){
      let datetime = new Date(msec);
      let year = datetime.getFullYear();
      let month = datetime.getMonth();
      let result = year +
                 '-' +
                 ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1));
      return result;
    },
    msToDate (msec) {
        let datetime = new Date(msec);
        let year = datetime.getFullYear();
        let month = datetime.getMonth();
        let date = datetime.getDate();
        let hour = datetime.getHours();
        let minute = datetime.getMinutes();
        let second = datetime.getSeconds();

        let result1 = year +
                    '-' +
                    ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
                    '-' +
                    ((date + 1) < 10 ? '0' + date : date) +
                    ' ' +
                    ((hour + 1) < 10 ? '0' + hour : hour) +
                    ':' +
                    ((minute + 1) < 10 ? '0' + minute : minute) +
                    ':' +
                    ((second + 1) < 10 ? '0' + second : second);

        let result2 = year +
                    '-' +
                    ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
                    '-' +
                    ((date + 1) < 10 ? '0' + date : date);

        let result = {
            hasTime: result1,
            withoutTime: result2
        };

        return result;
    },
    handleAvatarSuccess(res, file) {
      if(res.IsSuccess){
        this.$message.success('上传成功');
        this.$refs.upload.clearFiles()
        this.addDialog = false;
      }else{
        this.$message.error(res.Message);
        this.$refs.upload.clearFiles();
      }
    },
    handleFileError(err, file, fileList){
      if(err.status === 500){
        this.$message.error('上传失败，请检查文件填写格式是否正确');
        this.$refs.upload.clearFiles()
      }
    },
    beforeAvatarUpload(file) {
      // const isExcle = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      // if (!isExcle) {
      //   this.$message.error('文件格式错误，只允许上传excle文件');
      //   this.$refs.upload.clearFiles()
      // }
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isLt2M) {
      //   this.$message.error('上传文件大小不能超过 2MB!');
      //   this.$refs.upload.clearFiles()
      // }
      return true; //isExcle && isLt2M;
    },
    submitUpload() {
      this.$refs.upload.submit();
    }
  }
}
</script>
<style lang='scss' type='text/scss' rel='stylesheet/scss'>
.container-main{
  width: 100% !important;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .btn-row{
    margin-bottom:10px;
  }
  .btn-row .el-button+.el-button{
    margin-left:0px;
  }
</style>
